/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.trader.user;

import ca.trader.enterprisebeans.UserBeanLocal;
import ca.trader.except.InvalidHttpRequestException;
import ca.trader.except.LocationNotFoundException;
import ca.trader.except.PasswordLengthException;
import ca.trader.except.UserAlreadyExistsException;
import ca.trader.logger.TraderLogger;
import ca.trader.regions.Location;
import ca.trader.utils.DebugUtils;
import ca.trader.utils.HttpConsts;
import ca.trader.utils.ObjectFactory;
import ca.trader.utils.PasswordUtils;
import ca.trader.utils.URLUtils;
import ca.trader.utils.UserValidationUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Ahsan
 */
@WebServlet(name = "DoRegister", urlPatterns =
{
	 "/DoRegister"
})
public class DoRegister extends HttpServlet
{
	 private static final String _className = DoAuthenticate.class.getName();

	 private static final String PARAM_EMAIL = "email";
	 private static final String PARAM_FIRST_NAME = "firstName";
	 private static final String PARAM_LAST_NAME = "lastName";
	 private static final String PARAM_PASSWORD = "password";
	 private static final String PARAM_COUNTRY = "country";
	 private static final String PARAM_REGION = "region";
	 private static final String PARAM_CITY = "city";
	 	 
	 @EJB
	 UserBeanLocal userBean;

	 /**
	  * Processes requests for both HTTP
	  * <code>GET</code> and
	  * <code>POST</code> methods.
	  *
	  * @param request servlet request
	  * @param response servlet response
	  * @throws ServletException if a servlet-specific error occurs
	  * @throws IOException if an I/O error occurs
	  */
	 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	 {
		  String _methodName = "processRequest";

		  response.setContentType("text/plain;charset=UTF-8");
		  PrintWriter out = response.getWriter();

		  TraderLogger.logInfo(_className, _methodName, "Starting servlent: " + this.getServletName());


		  JSONObject jsonObject = new JSONObject(); // for output

		  boolean wasSuccess = false;
		  boolean wasUnknownFailure = false;

		  String failureReason = "";
		  String unknownReasonStackTrace = "";

		  try
		  {

			   TraderLogger.logInfo(_className, _methodName, "Validating POST PARAMETERS - Step 1");
			   if (request.getParameter(PARAM_EMAIL) == null || request.getParameter(PARAM_FIRST_NAME) == null || request.getParameter(PARAM_LAST_NAME) == null || request.getParameter(PARAM_PASSWORD) == null || request.getParameter(PARAM_COUNTRY) == null || request.getParameter(PARAM_REGION) == null || request.getParameter(PARAM_CITY) == null)
			   {
				    throw new InvalidHttpRequestException("Invalid Request");
			   }		   
			   

			   String countryName = request.getParameter(PARAM_COUNTRY).trim();
			   String regionName = request.getParameter(PARAM_REGION).trim();
			   String city = request.getParameter(PARAM_CITY).trim();
			   
			   String userFirstName = request.getParameter(PARAM_FIRST_NAME).trim();
			   String userLastName = request.getParameter(PARAM_LAST_NAME).trim();
			   String userEmail = request.getParameter(PARAM_EMAIL).trim();
			   String userCryptedPassword = PasswordUtils.cryptPasswordString(request.getParameter(PARAM_PASSWORD));
			   
			   
			   User user = ObjectFactory.createUser(userEmail, userFirstName, userLastName, userCryptedPassword, false, countryName, regionName, city);


			   TraderLogger.logInfo(_className, _methodName, "Validating POST PARAMETERS - Step 2");

			   UserValidationUtils.validateUser(user, request.getParameter(PARAM_PASSWORD));

			   TraderLogger.logInfo(_className, _methodName, "Registering user");


			   UserActivationDesc desc = new UserActivationDesc();
			   desc.setActivationID(UUID.randomUUID().toString());
			   desc.setUser(user);

			   userBean.saveUserWithActivationDesc(desc);


			   TraderLogger.logInfo(_className, _methodName, "Successfully registered user");

			   //        HttpUtils.sendActivationEmail (request, desc.getUser().getEmail(), desc.getActivationID());
			   //send email here

			   wasSuccess = true;
		  }
		  catch (InvalidHttpRequestException e)
		  {
			   wasSuccess = false;
			   failureReason = "Invalid request.  Please request from " + URLUtils.getMainWebpage(request) + "/" + HttpConsts.REGISTER_JSP_PAGE;

		  }
		  catch (UserAlreadyExistsException e)
		  {
			   wasSuccess = false;
			   failureReason = e.getMessage();
		  }
		  catch (LocationNotFoundException e)
		  {
			   wasSuccess = false;
			   failureReason = e.getMessage();
		  }
		  /*catch (UserAlreadyExistsPendingActivationException e)
		   {
		   wasSuccess = false;
                           
                          
		   failureReason = e.getMessage();
		   }*/
		  catch (PasswordLengthException e)
		  {
			   wasSuccess = false;
			   failureReason = e.getMessage();
		  }
		  catch (Exception e)
		  {

			   wasSuccess = false;
			   failureReason = "Unknown error: " + e.getMessage();

			   wasUnknownFailure = true;
			   unknownReasonStackTrace = DebugUtils.getStackTraceAsString(e);

		  }
		  finally
		  {
			   if (wasUnknownFailure)
			   {
				    TraderLogger.logSevere(_className, _methodName, failureReason, unknownReasonStackTrace);
			   }
			   try
			   {
				    jsonObject.put("success", wasSuccess);

				    if (!wasSuccess)
				    {
						jsonObject.put("reason", failureReason);
						TraderLogger.logInfo(_className, _methodName, "Unable to register user: " + failureReason);
				    }
				    out.print(jsonObject.toString());
			   }
			   catch (JSONException ex)
			   {
			   }

			   out.close();


			   TraderLogger.logInfo(_className, _methodName, "Exiting servlent: " + this.getServletName());

			   TraderLogger.exiting();
		  }
	 }

	 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
	 /**
	  * Handles the HTTP
	  * <code>GET</code> method.
	  *
	  * @param request servlet request
	  * @param response servlet response
	  * @throws ServletException if a servlet-specific error occurs
	  * @throws IOException if an I/O error occurs
	  */
	 @Override
	 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	 {
		  processRequest(request, response);
	 }

	 /**
	  * Handles the HTTP
	  * <code>POST</code> method.
	  *
	  * @param request servlet request
	  * @param response servlet response
	  * @throws ServletException if a servlet-specific error occurs
	  * @throws IOException if an I/O error occurs
	  */
	 @Override
	 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	 {
		  processRequest(request, response);
	 }

	 /**
	  * Returns a short description of the servlet.
	  *
	  * @return a String containing servlet description
	  */
	 @Override
	 public String getServletInfo()
	 {
		  return "Short description";
	 }// </editor-fold>

}
